package com.cy.stores.controller;

import com.cy.stores.pojo.User;
import com.cy.stores.service.IUserService;
import com.cy.stores.service.ex.InsertException;
import com.cy.stores.service.ex.UsernameDuplicateException;
import com.cy.stores.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("users")
public class UserController extends BaseController{
    @Autowired
    private IUserService userService;
    @RequestMapping("reg")
    public JsonResult<Void> reg(User user){
        userService.reg(user);
        return new JsonResult<>(OK);
    }
    //优化控制器，提取公共类
    //    @RequestMapping("reg")
//    public JsonResult<Void> register(User user){
//        JsonResult<Void> result = new JsonResult<>();
//        try {
//            userService.reg(user);
//            result.setState(200);
//        } catch (UsernameDuplicateException e) {
//            result.setState(4000);
//            result.setMessage("用户名已经被占用");
//        }catch (InsertException e){
//            result.setState(5000);
//            result.setMessage("注册失败，请联系系统管理员");
//        }
//
//        return result;
//    }
    @RequestMapping("login")
    public JsonResult<User> login(String username, String password, HttpSession session){
        User data = userService.login(username, password);
//        从session中完成数据的绑定
        session.setAttribute("uid", data.getUid());
        session.setAttribute("username", data.getUsername());
        //获取session中绑定的数据
        System.out.println("uid="+getUidFromSession(session));
        System.out.println("username="+getUserNameFromSession(session)+"登陆成功");

        return new JsonResult<User>(OK,data);
    }

}
